import * as Cesium from "cesium";
export const useCesium = (id: string) => {
  let viewer: Cesium.Viewer;
  const initViewer = () => {
    Cesium.Camera.DEFAULT_VIEW_RECTANGLE = Cesium.Rectangle.fromDegrees(
      80,
      20,
      120,
      40
    );

    const tdt = new Cesium.WebMapTileServiceImageryProvider({
      url: "http://t{s}.tianditu.gov.cn/img_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={TileMatrix}&TILEROW={TileRow}&TILECOL={TileCol}&tk=a91f023141dfeda6a7929e856fe1c520",
      style: "default",
      format: "tiles",
      // maximumLevel: 10,
      subdomains: ["0", "1", "2", "3", "4", "5", "6"],
      layer: "img",
      tileMatrixSetID: "w",
    });

    viewer = new Cesium.Viewer(id, {
      selectionIndicator: false,
      infoBox: false,
      timeline: false,
      animation: false,
      geocoder: false,
      homeButton: false,
      baseLayerPicker: false,
      navigationHelpButton: false,
      sceneModePicker: false,
      fullscreenButton: false,
      baseLayer: new Cesium.ImageryLayer(tdt),

      terrain: new Cesium.Terrain(
        Cesium.CesiumTerrainProvider.fromUrl("http://data.mars3d.cn/terrain")
      ),
    });
    viewer.creditDisplay.container.style.display = "none";
    // viewer.scene.globe.depthTestAgainstTerrain = true;

    return viewer;
  };

  const windowPoint2Cartesian3 = (
    point: Cesium.Cartesian2,
    v: Cesium.Viewer = viewer
  ) => {
    const ray = v.camera.getPickRay(point);

    return v.scene.globe.pick(ray!, v.scene)!;
  };

  //参数为什么类型,可根据函数API去传参
  //len(单位:m)
  //返回的类型可根据API转换坐标即可
  function ByDirectionAndLen(
    position: Cesium.Cartesian3,
    angle: number,
    len: number
  ) {
    let matrix = Cesium.Transforms.eastNorthUpToFixedFrame(position);

    let mz = Cesium.Matrix3.fromRotationZ(Cesium.Math.toRadians(angle || 0));

    let rotationZ = Cesium.Matrix4.fromRotationTranslation(mz);
    Cesium.Matrix4.multiply(matrix, rotationZ, matrix);

    let result = Cesium.Matrix4.multiplyByPoint(
      matrix,
      new Cesium.Cartesian3(0, len, 0),
      new Cesium.Cartesian3()
    );
    return result;
  }

  return { initViewer, windowPoint2Cartesian3, ByDirectionAndLen };
};
